package com.example.gamecard

import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.ViewModel
import kotlin.random.Random

class GameCardViewModel : ViewModel() {
    private val _shuffledCards = mutableStateListOf<String>()
    val shuffledCards: List<String>
        get() = _shuffledCards

    private val _players = mutableStateListOf<Player>()
    val players: List<Player>
        get() = _players

    private var _winner = ""
    val winner: String
        get() = _winner

    fun startGame() {
        shuffleCards()
        dealCards()
        findWinner()
    }

    private fun shuffleCards() {
        val allCards = listOf(
            "2@", "2#", "2^", "2*", "3@", "3#", "3^", "3*", "4@", "4#", "4^", "4*",
            "5@", "5#", "5^", "5*", "6@", "6#", "6^", "6*", "7@", "7#", "7^", "7*",
            "8@", "8#", "8^", "8*", "9@", "9#", "9^", "9*", "10@", "10#", "10^", "10*",
            "J@", "J#", "J^", "J*", "Q@", "Q#", "Q^", "Q*", "K@", "K#", "K^", "K*",
            "A@", "A#", "A^", "A*"
        )
        val random = Random(System.currentTimeMillis())
        _shuffledCards.clear()
        _shuffledCards.addAll(allCards.shuffled(random))
    }

    private fun dealCards() {
        _players.clear()
        for (i in 0 until 4) {
            _players.add(Player(mutableListOf()))
        }
        _shuffledCards.forEachIndexed { index, card ->
            _players[index % 4].cards.add(card)
        }
    }

    private fun findWinner() {
        val playerGroups = _players.map { player ->
            player.cards.groupBy { card ->
                val (letterNumber, symbol) = card.split("(?=[@#^*])".toRegex())
                letterNumber
            }.map { (letterNumber, symbols) ->
                Group(letterNumber, symbols.size, symbols)
            }
        }
        val maxGroup = playerGroups.flatten().reduce { max, group ->
            if (group.count > max.count || (group.count == max.count && group.letterNumber > max.letterNumber)) group else max
        }
        _winner = if (maxGroup.count > 0) {
            "玩家 ${playerGroups.indexOfFirst { it.any { g -> g.letterNumber == maxGroup.letterNumber && g.count == maxGroup.count } } + 1}"
        } else {
            "没有赢家"
        }
    }
}

data class Player(val cards: MutableList<String>)
data class Group(val letterNumber: String, val count: Int, val symbols: List<String>)